package cn.bob.org.service.impl;

import cn.bob.basic.config.BussinessException;
import cn.bob.basic.jwt.LoginContext;
import cn.bob.basic.query.BaseQuery;
import cn.bob.basic.utils.*;
import cn.bob.org.domain.Employee;
import cn.bob.org.domain.Shop;
import cn.bob.org.domain.ShopAuditLog;
import cn.bob.org.eum.ShopStateEum;
import cn.bob.org.mapper.EmployeeMapper;
import cn.bob.org.mapper.ShopAuditLogMapper;
import cn.bob.org.mapper.ShopMapper;
import cn.bob.org.service.IShopService;
import cn.bob.basic.service.impl.BaseServiceImpl;
import cn.bob.basic.vo.ShopEchartsVo;
import cn.bob.user.domain.Logininfo;
import cn.bob.user.mapper.LogininfoMapper;
import cn.bob.user.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bob
 * @since 2022-10-15
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
@Autowired
private ShopMapper shopMapper;
@Autowired
private EmployeeMapper employeeMapper;
@Autowired
private ShopAuditLogMapper auditLogMapper;
@Autowired
private LogininfoMapper logininfoMapper;


    @Override
    public void settlement(Shop shop) {
        Employee admin = shop.getAdmin();
        Employee employee = getEmployee(shop, admin);
        //判断是否已经创建该管理员
        if (employee == null){  //为空创建
            //获取盐值
            String salt = StrUtils.getComplexRandomString(32);
            //生成密码
            String pwd = MD5Utils.encrypByMd5(salt + admin.getPassword());
            admin.setSalt(salt);
            admin.setPassword(pwd);
            //添加logininfo信息
            Logininfo logininfo = empConventLog(admin);
            logininfo.setType(0);
            logininfoMapper.add(logininfo);
            //添加logininfo的id
            admin.setLogininfoId(logininfo.getId());
            employeeMapper.add(admin);
        }
        //创建店铺，店铺已经判断了是否储存在
        shopMapper.add(shop);


        //修改employee中的shoptid以及shop中的adminid
        admin.setShopId(shop.getId());
        employeeMapper.update(admin);


        Shop shop1 = new Shop();
        shop1.setId(shop.getId());
        shop1.setAdminId(admin.getId());
        shopMapper.update(shop1);
    }
    //将employee转换为logininfo
    public Logininfo empConventLog(Employee employee){
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        return logininfo;
    }
    //新增店铺中的百度AI验证
    @Override
    public void addBaiDuAi(Shop shop) {
        //百度 AI
        //判断店铺的名称是否违规
        Boolean aboo = BaiduAuditUtils.TextCensor(shop.getName());
        Boolean lean = BaiduAuditUtils.ImgCensor(shop.getLogo());
        if (!aboo){
            throw new BussinessException("请输入合法的名称！！");
        }
        if (!lean){
            throw new BussinessException("图片不合规！！！");
        }
    }

    /**
     * 店铺审核通过的接口
     * 审核通过将店铺的状态改为待激活/审核通过
     * 将审核人以及 操作 备注 添加到日志表
     * 发送邮件激活
     * @param auditLog
     */
    @Override
    public void pass(ShopAuditLog auditLog) {
        //判断备注不能为空
        if (StringUtils.isBlank(auditLog.getNote())){
            throw new BussinessException("备注不能为空！！");
        }
        //替换logininfo的id为emp的id
        Employee byName = employeeMapper.findByLogid(auditLog.getAuditId());
        auditLog.setAuditId(byName.getId());

        //修改状态
        Shop shop = new Shop();
        shop.setId(auditLog.getShopId());
        shop.setState(1);
        shopMapper.update(shop);
        //添加日志到表中
        //登录
        auditLog.setState(1);
        auditLogMapper.add(auditLog);

        //todo 发送邮件 抽取为工具类
        try {
            EmailUtil.sendMail("209545769@qq.com","209545769@qq.com",
                    "审核通过请激活：http://localhost:8080/shop/active/"+auditLog.getShopId(),
                    "D:/桌面/study/74882994_590610338351366_111836065010024448_o.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void active(Long id) {
        Shop byId = shopMapper.findById(id);
        byId.setState(2);
        shopMapper.update(byId);
    }

    //驳回
    @Override
    public void reject(ShopAuditLog auditLog) {
        //判断备注不能为空
        if (StringUtils.isBlank(auditLog.getNote())){
            throw new BussinessException("备注不能为空！！");
        }
        //替换logininfo的id为emp的id
        Employee byName = employeeMapper.findByLogid(auditLog.getAuditId());
        auditLog.setAuditId(byName.getId());

        //修改状态
        Shop shop = new Shop();
        shop.setId(auditLog.getShopId());
        shop.setState(-1);
        shopMapper.update(shop);

        //添加日志到表中
        //写登录
        auditLog.setState(0);
        auditLogMapper.add(auditLog);

        //todo 发送邮件 抽取为工具类
        try {
            EmailUtil.sendMail("209545769@qq.com","209545769@qq.com",
                    "审核驳回请重新填写店铺审核：http://localhost:8081/#/RegisterAgain?shopId="+auditLog.getShopId(),
                    "D:/桌面/study/74882994_590610338351366_111836065010024448_o.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Map<String, Object> echarts() {
        HashMap<String, Object> result = new HashMap<>();
        List<ShopEchartsVo> vo=shopMapper.echarts();
        List<Integer> x = vo.stream().map(ShopEchartsVo::getState).collect(Collectors.toList());
        List<Integer> y = vo.stream().map(ShopEchartsVo::getCount).collect(Collectors.toList());

        List<String> realX = new ArrayList<>();
        for (Integer xTemp : x) {
            String statename = ShopStateEum.getNameByCode(xTemp);
            realX.add(statename);
        }
        result.put("x",realX);
        result.put("y",y);
        return result;
    }
    //批量添加
    @Override
    public void addAll(List<Shop> shops) {
        shopMapper.addAll(shops);
    }

    private Employee getEmployee(Shop shop, Employee admin) {
        //判断传入的Shop名称是否为空
        if (StringUtils.isEmpty(shop.getName())){
            throw new BussinessException("店铺名称不能为空！！");
        }
        //校验两次密码是否一致
        if (!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BussinessException("两次密码不一致！！");
        }
        //百度 AI
        //判断店铺的名称是否违规
        Boolean aboo = BaiduAuditUtils.TextCensor(shop.getName());
        Boolean lean = BaiduAuditUtils.ImgCensor(shop.getLogo());
        if (!aboo){
            throw new BussinessException("请输入合法的名称！！");
        }
        if (!lean){
            throw new BussinessException("图片不合规！！！");
        }

        //判断店铺表是否已经存在
        Shop loadShop= shopMapper.findByName(shop.getName());
        if(loadShop!=null){
            throw new BussinessException("店铺已经存在！！");
        }
        //判断管理员是否存在并且是否已经管理了店铺

        Employee employee =employeeMapper.findByName(admin.getUsername());
        if (employee != null &&  employee.getShopId() != null){
            Shop byId = shopMapper.findById(employee.getShopId());
            if (byId.getAdminId().equals(employee.getId())) {
                throw new BussinessException("该管理员已经绑定店铺！");
            }
        }
        return employee;
    }

    @Override
    public PageList<Shop> queryByPage(BaseQuery query) {
        PageList<Shop> shopPageList = super.queryByPage(query);
        List<Shop> rows = shopPageList.getRows();

        //将子存储到集合中
        for (Shop row : rows) {
            Long id = row.getId();
            List<ShopAuditLog> slogs = auditLogMapper.findByShopId(id);
            row.setAuditLogs(slogs);
        }


        shopPageList.setRows(rows);
        return shopPageList;
    }


}
